package cn.edu.nuc.ssm.controller;

import cn.edu.nuc.ssm.entity.Category;
import cn.edu.nuc.ssm.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Administrator on 2017/5/5.
 */
@Controller
@RequestMapping("/category")
public class BackCategoryController {

    @Autowired
    private CategoryService categoryService;

    @RequestMapping(value = "/tolist",method = RequestMethod.GET)
    public String tolist() {

        return "back/category/list";

    }

    @ResponseBody
    @RequestMapping(value = "/listcategory",method = RequestMethod.GET)
    public List<Category> list(){

        return categoryService.listCategory();
    }

    @ResponseBody
    @RequestMapping(value = "/updatename",method = RequestMethod.POST)
    public String updatename(@RequestBody Category category){

        categoryService.updatename(category.getId(),category.getName());

        return "success";
    }


    @RequestMapping(value = "/toadd",method = RequestMethod.GET)
    public String toadd(){

        return "back/category/add";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(Category category, HttpSession session){

        List<Category> categoryList = categoryService.findByName(category.getName());

        if ( categoryList != null && categoryList.size() > 0 ){

            session.setAttribute("msg","类别已经存在了");
            return "back/category/add";
        }

        categoryService.insert(category);
        session.setAttribute("msg","");

        return "redirect:/category/tolist";
    }

    @ResponseBody
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public String delete(Integer id){

        categoryService.delete(id);

        return "success";
    }

}
